package com.luoxiang.socialandroid.dialog

import android.content.Context
import android.util.Log
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.luoxiang.lib_common.common.Constants.MmkvConst.USER_NAME
import com.luoxiang.socialandroid.R
import com.luoxiang.socialandroid.databinding.DialogGiftSuspensionBinding
import com.luoxiang.socialandroid.utils.MmkvUtil
import com.lxj.xpopup.core.PositionPopupView
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.msg.model.IMMessage
import com.netease.nimlib.sdk.uinfo.UserService
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo
import com.netease.yunxin.kit.chatkit.ui.custom.GiftAttachment
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class GiftSuspensionDialog(context: Context) : PositionPopupView(context) {
    private lateinit var mViewBinding: DialogGiftSuspensionBinding
    private lateinit var data: IMMessage

    override fun getImplLayoutId() = R.layout.dialog_gift_suspension

    override fun onCreate() {
        super.onCreate()
        delayDismiss(3000L)
        mViewBinding = DialogGiftSuspensionBinding.bind(popupImplView)
        val attachment = data.attachment
        if (attachment is GiftAttachment) {
            Glide.with(context)
                .load(attachment.data.gift.src)
                .into(mViewBinding.imageGift)
            mViewBinding.textGiftNumber.text = "X${attachment.data.number}"
        } else {
            dismiss()
        }
        mViewBinding.textToName.text = MmkvUtil.decodeString(USER_NAME)
        mViewBinding.textName.text = data.fromNick
        var user: NimUserInfo? = null
        var count = 1
        while(user == null){
            Log.d("userService","第$count 次获取")
            user = NIMClient.getService(UserService::class.java).getUserInfo(data.fromAccount)
            count++
        }
        Glide.with(context)
            .load(user.avatar)
            .apply(RequestOptions.bitmapTransform(CircleCrop()))
            .into(mViewBinding.imageHead)
    }

    fun setData(data: IMMessage) {
        this.data = data
    }
}